#include "tdlgconfig.h"
#include "ui_tdlgconfig.h"
#include "tlr.h"
#include <QRadioButton>

TDlgConfig::TDlgConfig(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::TDlgConfig)
{
    //UI初始化
    {
        ui->setupUi(this);
        ui->wgtBK->setProperty("white",true);
        ui->btnOK->setProperty("red",true);
        ui->lbNetTitle->setProperty("gray",true);
        ui->gbMyIP->setMinimumHeight(100);
        ui->btnOK->setMinimumSize(QSize(100,30));
        ui->btnOK->setMaximumSize(QSize(100,30));
        dataToUI(TUIType::uiFrame);
        setWindowTitle(tr("软件设置"));
    }
    //信号槽
    {
        //保存按钮点击
        connect(ui->btnOK,&QPushButton::clicked,this,&TDlgConfig::slotBtnOKClicked);
    }
}

TDlgConfig::~TDlgConfig()
{
    delete ui;
}

/*
 * UI操作
 * nuitype : ui操作类型
 */
void TDlgConfig::dataToUI(TDlgConfig::TUIType nuitype)
{
    switch (nuitype) {
    //区域表格显示
    case TUIType::uiFrame:{
        auto nlistbutton = m_bgpMyIP->buttons();
        for(auto nbutton:nlistbutton){
            m_bgpMyIP->removeButton(nbutton);
        }
        if(ui->gbMyIP->layout()){
            QLayoutItem *child;
            while ((child = ui->gbMyIP->layout()->takeAt(0)) != nullptr) {
                delete child->widget();
                delete child;
            }
            delete ui->gbMyIP->layout();
        }
        TMyIP nmyip = TLR::get()->getMyIP();
        QVBoxLayout *vbox = new QVBoxLayout;
        auto nlistip = TLR::getAllAddressIPv4();
        for(const QHostAddress &nip:nlistip){
            QRadioButton* pradiobtn = new QRadioButton;
            //IP
            pradiobtn->setText(nip.toString());
            if(nip.toIPv4Address() == TLR::ip4toAddress(nmyip.ip).toIPv4Address()) {
                pradiobtn->setChecked(true);
            }
            //加入容器
            vbox->addWidget(pradiobtn);
            //增加按钮
            m_bgpMyIP->addButton(pradiobtn);
        }
        ui->gbMyIP->setLayout(vbox);
        break;
    }
    }
}

/*
 * 保存按钮点击
 */
void TDlgConfig::slotBtnOKClicked()
{
    QAbstractButton *pbtn = m_bgpMyIP->checkedButton();
    if(pbtn) {
        TLR::get()->setMyIP(QHostAddress(pbtn->text()));
    }
    accept();
}
